<template>
  <el-form class="query-container" ref="queryFormRef" :model="queryParams" :inline="true" @submit.native.prevent>
    <el-form-item label="用户ID" prop="userId">
      <el-input
          v-model="queryParams.userId"
          clearable
          placeholder="请输入用户ID"
          @keyup.enter.native="handleQuery"
      />
    </el-form-item>


    <el-form-item>
      <el-button type="primary" @click="handleQuery">搜索</el-button>
      <el-button @click="resetQuery">重置</el-button>
    </el-form-item>
  </el-form>

  <div class="inner-container">
    <el-row :gutter="10" style="margin-bottom:8px">
    </el-row>
    <el-table v-loading="loading" :data="licenseTableData" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="30"/>
      <el-table-column prop="userId" label="用户ID"/>
      <el-table-column prop="name" label="姓名"/>
      <el-table-column prop="gender" label="性别" :formatter="genderFormatter"/>
      <el-table-column prop="birthday" label="生日"  style="width:50%;" show-overflow-tooltip>
        <template #default="scope">
          <div>{{scope.row.birthday}}</div>
        </template>
      </el-table-column>

      <el-table-column prop="frontImage" label="驾照" show-overflow-tooltip>
        <template #default="scope">
          <div><img :src="scope.row.frontImage" style="width: 75px;height: 55px;" alt=""></div>
        </template>
      </el-table-column>

      <el-table-column >
        <template #default="scope">
          <el-button type="primary" link icon="View" @click="showLicenseImg(scope.row.frontImage)">查看</el-button>

        </template>
      </el-table-column>
      <el-table-column prop="validationStatus" label="是否有效" :formatter="validationStatusFormatter"/>

      <el-table-column prop="licenseNumber" label="驾照号码"/>

      <el-table-column prop="validDateStart" label="证件有效期起始日期"  show-overflow-tooltip>
        <template #default="scope">
          <div>{{scope.row.validDateStart}}</div>
        </template>
      </el-table-column>

      <el-table-column prop="validDateEnd" label="截止日期"  show-overflow-tooltip>
        <template #default="scope">
          <div>{{scope.row.validDateEnd}}</div>
        </template>
      </el-table-column>

      <el-table-column prop="nationality" label="国籍"/>
      <el-table-column prop="address" label="地址"/>

      <el-table-column prop="emergencyContact" label="紧急联系人"/>
      <el-table-column prop="emergencyPhone" label="紧急电话"/>
      <el-table-column prop="auditing" label="审核状态" :formatter="auditingStatusFormatter"/>
      <el-table-column prop="applicationId" label="审核申请ID"/>

      <el-table-column label="操作" fixed="right" width="150">
        <template #default="scope">
          <el-button type="primary" link icon="Edit" @click="showEditDialog(scope.row)">审核</el-button>
          <el-button type="primary" link icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <br>
    <el-pagination
        :total="total"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <el-dialog v-model="dialogVisible" :title="dialogTitle" :before-close="closeDialog" append-to-body>
      <el-form ref="dialogFormRef" :model="formData" :rules="formRules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户ID" prop="userId">
              <el-input v-model="formData.userId" placeholder="请输入用户ID" readonly/>
            </el-form-item>
          </el-col>


        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name" placeholder="请输入姓名" readonly/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>

          <el-col :span="12">
            <el-form-item label="驾照号码" prop="licenseNumber">
              <el-input v-model="formData.licenseNumber" placeholder="请输入驾照号码" readonly/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <!-- 驾照正面上传 -->
            <el-form-item label="驾照正面" prop="frontImageUrl">
              <el-upload
                  action=""
                  list-type="picture-card"
                  v-model:file-list="thumbnailTempList"
                  :http-request="uploadFileThumbnail"
                  :limit="1"
                  :disabled="true"
              >
                <!-- 自定义文件列表模板，仅显示已上传的图片 -->
                <template #file="{ file }">
                  <div v-if="file.url">
                    <!-- 显示文件的缩略图 -->
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>
                    <!-- 文件操作按钮容器 -->
                    <span class="el-upload-list__item-actions">
              <!-- 预览图片按钮 -->
              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <el-icon><zoom-in/></el-icon>
              </span>
            </span>
                  </div>
                </template>
              </el-upload>

              <!-- 图片预览对话框 -->
              <el-dialog v-model="dialogImageVisible" style="z-index: 999; width: 70%; padding: 50px;">
                <img :src="dialogImageUrl" alt="Preview Image" style="width: 100%;"/>
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="12">
            <el-form-item label="审核"  prop="auditing" >
              <el-select v-model="formData.auditing" placeholder="请选择审核状态" style="width:96%;">
                <el-option value="0" label="通过"></el-option>
                <el-option value="1" label="审核中"></el-option>
                <el-option value="2" label="认证失败"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      <template #footer class="dialog-footer">
        <el-button type="primary" @click="saveDriverLicense">确定</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </template>
    </el-dialog>
    <el-dialog title="查看图片" v-model="imagDialogVisible" width="800" >
      <img alt="" :src="imgUrl" style="width: 700px; margin: 0 auto; display: block"/>
    </el-dialog>
  </div>


</template>

<script setup>
import {computed, nextTick, onMounted, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import ElIconPicker from '@/components/ElIconPicker'
import request from '@/utils/request'




const loading = ref(false)
const queryFormRef = ref()
const queryParams = ref({pageNum: 1, pageSize: 10})
const total = ref(0)
const licenseTableData = ref([])
const selectedIds = ref([])
const imgUrl= ref('')
//定义变量用来保存起止时间
const times = ref([]);

const loadDriverlicense = () => {
  loading.value = true
  request.get('/api/bus/users/driverlicense', {
    params: queryParams.value
  }).then(res => {
    total.value = res.data.total
    licenseTableData.value = res.data.list
    loading.value = false
  })
}
loadDriverlicense();


const showLicenseImg = (frontImage)=>{
  imgUrl.value=frontImage;
  imagDialogVisible.value=true;
}
//---------------------------------------------
const listData = () => {
  loading.value = true
  request.get('/api/bus/users/driverlicense', {
    params: queryParams.value
  }).then(res => {
    total.value = res.data.total
    licenseTableData.value = res.data.list
    loading.value = false
  })
}
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

const handleQuery = () => {
  queryParams.value.pageNum = 1
  listData()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  listData()
}

const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  listData()
}
const showEditDialog = (row) => {
  let id = row.id || selectedIds.value
  request.get(`/api/bus/users/driverlicense/${id}`)
      .then(res => {
        formData.value = res.data
        formData.value.auditing=formData.value.auditing.toString()
        dialogTitle.value = '驾照审核'
        dialogVisible.value = true
        thumbnailTempList.value = [{url:res.data.frontImage}]
      })
}
const bannerList = ref([])

const getBannerList = () => {
  request.get(`/api/bus/users/driverlicense/`)
      .then(res => {
        bannerList.value = res.data
      })
}


const handleDelete = (row) => {
  let ids = row ? [row.id] : [...selectedIds.value]
  if (ids.length === 0) {
    ElMessage.error('请选择要删除的记录')
    return
  }
  ElMessageBox.confirm('确定删除吗？', '提示', {
    type: 'warning'
  }).then(() => {
    request.delete(`/api/bus/users/driverlicense?ids=${ids}`)
        .then(res => {
          selectedIds.value.length = 0
          listData()
          ElMessage.success('删除成功')
        })
  }).catch(() => {})
}
// 新增表单--------------------------------------------------
const dialogTitle = ref('')
const dialogVisible = ref(false)
const dialogFormRef = ref()
const imagDialogVisible = ref(false)
const frontImage= ref('')

const formData = ref({
  id:undefined,
  userid:undefined,
  name: undefined,
  gender:undefined,
  birthday:undefined,
  frontImage:[],
  back_image:[],
  licenseNumber:undefined,
  validDateStart:undefined,
  validDateEnd:undefined ,
  validationStatus:undefined,
  nationality:undefined,
  address:undefined,
  emergencyContact:undefined,
  emergencyContactPhone:undefined,
  auditing:undefined,
  applicationId:undefined,
  createTime:undefined,
  createBy:undefined,
  updateTime:undefined,
  updateBy:undefined
})
const showImg = (i)=>{
  frontImage.value=i;
  imagDialogVisible.value=true;
}
const formRules = ref({
  // name: [{required: true, message: '姓名为必填项'}],
})
const showAddDialog = () => {

  dialogTitle.value = '新增驾照信息'
  dialogVisible.value = true
}





const saveDriverLicense = () => {
  dialogFormRef.value.validate(valid => {
    if (!valid) {
      ElMessage.error('请正确填写参数')
      return;
    }
    const id = formData.value.id
    request({
      url: '/api/bus/users/driverlicense',
      method: id ? 'put' : 'post',
      data: formData.value
    }).then(res => {
      dialogVisible.value=false;
      loadDriverlicense();
      ElMessage.success(id ? '修改成功' : '新增成功')
    })
  })
}
//退出弹窗提示-----------------------
const closeDialog =() => {
  if (confirm("确认退出吗?")){
    formData.value= {
      name: undefined,
      frontImage: []
    }
  }
  dialogVisible.value=false;
}

//保存图片--------------------

// 导入Element Plus图标组件
import {Delete, Plus, ZoomIn} from '@element-plus/icons-vue';

// 定义一个响应式的数组，用于存储上传文件的列表
let thumbnailTempList = ref([]);
// 定义用于预览图片的URL的响应式引用
const dialogImageUrl = ref('');
// 定义用于控制预览对话框可见性的响应式引用
const dialogImageVisible = ref(false);
// 定义是否禁用删除和下载操作的响应式引用
const disabled = ref(false);

/**
 * 上传文件的处理函数
 * @param {Object} file - 包含上传文件信息的对象
 * 返回图片生成地址
 */
function uploadFileThumbnail(file){
  const formImgData = new FormData()
  formImgData.append('file',file.file)
  request({
    url: '/file/upload',
    method:'post',
    data: formImgData
  }).then(res => {
    file.onSuccess(res.data)
    dialogImageUrl.value=res.data;
    formData.value.frontImage = res.data;
  })
}

// 预览图片的处理函数
const handlePictureCardPreview = (file) => {
  // 设置预览图片的URL
  dialogImageUrl.value = file.url;
  // 显示预览对话框
  dialogImageVisible.value = true;
};

// 删除文件的处理函数
const handleRemove = (file) => {
  dialogImageUrl.value = '';// 清空当前预览图片
  thumbnailTempList.value = []; // 清空上传列表，如果列表只用于显示预览的话
  formData.value.frontImage = []; //清空当前表单图片数据
};

//性别显示转换
const genderFormatter = (row,column,cellValue,index)=>{
  if (cellValue==0){
    cellValue = '女';
  }else if (cellValue==1){
    cellValue = '男';
  }
  return cellValue;
}

//有效日期显示转换
const validationStatusFormatter = (row,column,cellValue,index)=>{
  if (cellValue==0){
    cellValue = '有效';
  }else if (cellValue==1){
    cellValue = '失效';
  }
  return cellValue;
}

//审核状态显示转换
const auditingStatusFormatter = (row,column,cellValue,index)=>{
  if (cellValue==0){
    cellValue = '通过';
  }else if (cellValue==1){
    cellValue = '审核中';
  }else if (cellValue==2){
    cellValue = '认证失败';
  }
  return cellValue;
}
</script>

<style scoped>

</style>
